import {
  useGetAccount,
  useLoginByPassword,
  useUpdateAccount,
} from '@/services/account';
import QUERY_KEYS from '@/services/constant';
import { beforeUpload } from '@/utils/upload';
import { AntDesignOutlined, LoadingOutlined } from '@ant-design/icons';
import {
  ModalForm,
  PageContainer,
  ProCard,
  ProFormRadio,
  ProFormText,
} from '@ant-design/pro-components';
import {
  Avatar,
  Descriptions,
  Form,
  Space,
  Upload,
  UploadFile,
  UploadProps,
} from 'antd';
import ImgCrop from 'antd-img-crop';
import { UploadChangeParam } from 'antd/es/upload';
import React, { useState } from 'react';
import { StyleEditIcon, StyleProCard } from './style';

interface AccountForm {
  email: string;
  password: string;
  phone: string;
}

interface BasicForm {
  nickName?: string;
  area?: string;
  sex?: string;
  birthday?: string;
}

interface UserForm {
  identity?: string;
  industry?: string;
  job?: string;
  interest?: string;
}

const PersonManagement: React.FC = () => {
  const [isEditAccount, setIsEditAccount] = useState<boolean>(false);
  const [isEditBasic, setIsEditBasic] = useState<boolean>(false);
  const [isEditUser, setIsEditUser] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [accountForm] = Form.useForm<AccountForm>();
  const [basicForm] = Form.useForm<BasicForm>();
  const [userForm] = Form.useForm<UserForm>();
  const { data: accountRes } = useGetAccount();
  const { mutateAsync: updateAccount } = useUpdateAccount();
  const { mutateAsync: loginByPassword } = useLoginByPassword(() => {}, false);

  const submitAccount = async (account: AccountForm) => {
    const res = await updateAccount({
      ...accountRes?.data,
      ...account,
    });
    if (res.code === 200) {
      loginByPassword({
        email: account.email,
        password: account.password,
      });
    }
  };

  const submit = async (basic: BasicForm | UserForm | { avatar: string }) => {
    updateAccount({
      ...accountRes?.data,
      ...basic,
    });
  };

  const handleChange: UploadProps['onChange'] = (
    info: UploadChangeParam<UploadFile>,
  ) => {
    if (info.file.status === 'uploading') {
      setIsLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      if (info.file.response.code === 200) {
        setIsLoading(false);
        submit({ avatar: info.file.response.data.url });
      }
    }
  };

  return (
    <PageContainer
      header={{
        title: '',
      }}
    >
      <Space direction="vertical" size="middle">
        <ProCard>
          <ImgCrop>
            <Upload
              name="file"
              className="avatar-uploader"
              maxCount={1}
              showUploadList={false}
              action={QUERY_KEYS.UPLOAD_IMAGE_URL}
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              <Avatar
                src={accountRes?.data?.avatar}
                size={100}
                icon={isLoading ? <LoadingOutlined /> : <AntDesignOutlined />}
              />
            </Upload>
          </ImgCrop>
        </ProCard>
        <StyleProCard
          title="账号管理"
          tooltip="修改需要验证"
          hoverable
          extra={
            <StyleEditIcon onClick={() => setIsEditAccount(true)} type="edit" />
          }
        >
          <Descriptions column={2} style={{ marginBlockEnd: -16 }}>
            <Descriptions.Item label="账号 ID">
              {accountRes?.data?.id}
            </Descriptions.Item>
            <Descriptions.Item label="密码">
              {accountRes?.data?.password}
            </Descriptions.Item>
            <Descriptions.Item label="邮箱">
              {accountRes?.data?.email}
            </Descriptions.Item>
            <Descriptions.Item label="手机">
              {accountRes?.data?.phone}
            </Descriptions.Item>
            {/* <Descriptions.Item label="账号注销">立即注销</Descriptions.Item> */}
          </Descriptions>
          <ModalForm<AccountForm>
            form={accountForm}
            autoFocusFirstInput
            modalProps={{
              destroyOnClose: true,
              onCancel: () => setIsEditAccount(false),
            }}
            open={isEditAccount}
            submitTimeout={2000}
            onFinish={async (values) => {
              submitAccount(values);
              setIsEditAccount(false);
              return true;
            }}
          >
            <ProFormText
              name="email"
              label="邮箱"
              initialValue={accountRes?.data?.email}
            />
            <ProFormText
              name="password"
              label="项目名称"
              initialValue={accountRes?.data?.password}
            />
            <ProFormText
              name="phone"
              label="手机号码"
              initialValue={accountRes?.data?.phone}
            />
          </ModalForm>
        </StyleProCard>
        <StyleProCard
          title="基本资料"
          hoverable
          extra={
            <StyleEditIcon onClick={() => setIsEditBasic(true)} type="edit" />
          }
        >
          <Descriptions column={2} style={{ marginBlockEnd: -16 }}>
            <Descriptions.Item label="用户昵称">
              {accountRes?.data?.nickName}
            </Descriptions.Item>
            <Descriptions.Item label="性别">
              {accountRes?.data?.sex}
            </Descriptions.Item>
            <Descriptions.Item label="所在地区">
              {accountRes?.data?.area}
            </Descriptions.Item>
            <Descriptions.Item label="出生日期">
              {accountRes?.data?.birthday}
            </Descriptions.Item>
          </Descriptions>
          <ModalForm<BasicForm>
            form={basicForm}
            autoFocusFirstInput
            modalProps={{
              destroyOnClose: true,
              onCancel: () => setIsEditBasic(false),
            }}
            open={isEditBasic}
            submitTimeout={2000}
            onFinish={async (values) => {
              submit(values);
              setIsEditBasic(false);
              return true;
            }}
          >
            <ProFormText
              name="nickName"
              label="用户昵称"
              initialValue={accountRes?.data?.nickName}
            />
            <ProFormRadio.Group
              name="sex"
              label="性别"
              initialValue={accountRes?.data?.sex}
              options={[
                { label: '男', value: '男' },
                { label: '女', value: '女' },
              ]}
            />
            <ProFormText
              name="area"
              label="所在地区"
              initialValue={accountRes?.data?.area}
            />
            <ProFormText
              name="birthday"
              label="生日"
              initialValue={accountRes?.data?.birthday}
            />
          </ModalForm>
        </StyleProCard>
        <StyleProCard
          title="个人信息"
          hoverable
          extra={
            <StyleEditIcon onClick={() => setIsEditUser(true)} type="edit" />
          }
        >
          <Descriptions column={2} style={{ marginBlockEnd: -16 }}>
            <Descriptions.Item label="身份">
              {accountRes?.data?.identity}
            </Descriptions.Item>
            <Descriptions.Item label="行业">
              {accountRes?.data?.industry}
            </Descriptions.Item>
            <Descriptions.Item label="职位">
              {accountRes?.data?.job}
            </Descriptions.Item>
            <Descriptions.Item label="感兴趣">
              {accountRes?.data?.interest}
            </Descriptions.Item>
          </Descriptions>
          <ModalForm<UserForm>
            form={userForm}
            autoFocusFirstInput
            modalProps={{
              destroyOnClose: true,
              onCancel: () => setIsEditUser(false),
            }}
            open={isEditUser}
            submitTimeout={2000}
            onFinish={async (values) => {
              submit(values);
              setIsEditUser(false);
              return true;
            }}
          >
            <ProFormText
              name="identity"
              label="身份"
              initialValue={accountRes?.data?.identity}
            />
            <ProFormText
              name="industry"
              label="行业"
              initialValue={accountRes?.data?.industry}
            />
            <ProFormText
              name="job"
              label="工作"
              initialValue={accountRes?.data?.job}
            />
            <ProFormText
              name="interest"
              label="感兴趣"
              initialValue={accountRes?.data?.interest}
            />
          </ModalForm>
        </StyleProCard>
      </Space>
    </PageContainer>
  );
};

export default PersonManagement;
